
#include "stdafx.h"
#include "exarchive.h"

//	*********************************
//	START original file: arccore.cpp

const unsigned BUF_SIZE = 512;

LPSTR ReadStringA(CArchive& ar, LPSTR lpsz, int & nMax)
{
	// if nMax is negative (such a large number doesn't make sense given today's
	// 2gb address space), then assume it to mean "keep the newline".
	int nRead(0), nStop = nMax - 1;
	char ch;

	TRY
	{
		while (nRead < nStop)
		{
			ar >> ch;

			// stop and end-of-line (trailing '\n' is ignored)
			if (ch == '\n' || ch == '\r')
			{
				if (ch == '\r') ar >> ch;
	// store the newline when called with negative nMax
	//				if ((int)nMax != nStop)
				lpsz[nRead++] = ch;
				break;
			}
//			if (!std::isprint(ch, std::locale()))
			lpsz[nRead++] = ch;
		}
	}
	CATCH(CArchiveException, e)
	{
		if (e && e->m_cause == CArchiveException::endOfFile)
		{
//			if(e) { delete e; }	//	DELETE_EXCEPTION(e);
			if (nRead == 0) return NULL;
		}
		else
		{
			THROW_LAST();
		}
	}
	END_CATCH

		nMax = nRead;	//	_dvk_dbg_
		lpsz[nRead] = '\0';

	return lpsz;
}

namespace exar {

bool MultiByte2WideStr(const CStringA & asource, CStringW & adest)
{
	WCHAR thebuf[BUF_SIZE + 1];
		* thebuf = 0;
	int thelen = ::MultiByteToWideChar(CP_UTF8, 
					MB_ERR_INVALID_CHARS,
					asource, asource.GetLength(),
					thebuf, BUF_SIZE);
	if ((0 < thelen) && (* thebuf) && (thelen < ERROR_NO_UNICODE_TRANSLATION)) 
	{
		if (thelen > BUF_SIZE) thelen = BUF_SIZE;
			thebuf[thelen] = 0;
			adest = thebuf;
		return true;
	}

		* thebuf = 0;
	thelen = ::MultiByteToWideChar(CP_THREAD_ACP, 
					MB_ERR_INVALID_CHARS,
					asource, asource.GetLength(),
					thebuf, BUF_SIZE);
	if ((0 < thelen) && (* thebuf) && (thelen < ERROR_NO_UNICODE_TRANSLATION)) 
	{
		if (thelen > BUF_SIZE) thelen = BUF_SIZE;
			thebuf[thelen] = 0;
			adest = thebuf;
		return true;
	}

	return false;
}

BOOL ReadStringA(CArchive& ar, CStringA& rString, bool * pzero)
{
	rString = "";    // empty string without deallocating
	const int nMaxSize = BUF_SIZE;
	LPSTR lpsz = rString.GetBuffer(nMaxSize);
	LPSTR lpszResult;
	int nLen;
	for (;;)
	{
		int nCount(nMaxSize);
		lpszResult = ReadStringA(ar, lpsz, nCount); // store the newline
		rString.ReleaseBuffer();

		nLen = (int) ::lstrlenA(lpsz);
		if (pzero)	//	_dvk_dbg_
			if (nCount > (nLen + 1))
				* pzero = true;

		// if string is read completely or EOF
		if ( (lpszResult == NULL) 
			|| (nLen < nMaxSize) || (lpsz[nLen-1] == '\n') )
		{
			break;
		}

		nLen = rString.GetLength();
		lpsz = rString.GetBuffer(nMaxSize + nLen) + nLen;
	}

	// remove '\n' from end of string if present
	lpsz = rString.GetBuffer(0);
	nLen = rString.GetLength();
	if (nLen != 0 && lpsz[nLen-1] == '\n')
		rString.GetBufferSetLength(nLen-1);

	return lpszResult != NULL;
}

}

//	FINISH original file: arccore.cpp
//	*********************************
